package com.kunpan.admin.service;

import com.kunpan.admin.common.Enum.FileStatusEnum;
import com.kunpan.admin.common.utils.file.FileUtils;
import com.kunpan.admin.entity.PanFile;
import com.kunpan.admin.mapper.PanFileMapper;
import com.kunpan.admin.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class TransactionService {
    @Autowired
    private PanFileMapper panFileMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 秒传处理核心逻辑
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public boolean handleFastUpload(PanFile existFile, Integer parentId, Long fileSize, String fileName, Integer userId) {
        // 如果存在父文件，更新父文件夹操作时间
        if (parentId != 0) {
            panFileMapper.updateFileUpdateTime(parentId, new Date());
        }

        // 构建新文件记录（提取方法）
        existFile.setFileName(FileUtils.newFileName(fileName));
        existFile.setCreateTime(new Date());
        existFile.setUpdateTime(new Date());
        existFile.setFileStatus(FileStatusEnum.NORMAL.getValue());
        existFile.setParentId(parentId);
        existFile.setUserId(userId);
        existFile.setId(null);

        // 事务操作（优化点：拆分用户空间更新逻辑）
        if (panFileMapper.insertFile(existFile) > 0) {
            userMapper.updateUserSpace(userId, fileSize);
            return true;
        }
        return false;
    }
}
